﻿package com.sgcc.nfc.lock.data.repository

import com.sgcc.nfc.lock.core.network.NetworkResult
import com.sgcc.nfc.lock.core.network.safeApiCall
import com.sgcc.nfc.lock.data.local.dao.OperationLogDao
import com.sgcc.nfc.lock.data.local.mapper.toDomain
import com.sgcc.nfc.lock.data.local.mapper.toEntity
import com.sgcc.nfc.lock.data.remote.api.LogApi
import com.sgcc.nfc.lock.domain.model.OperationLog
import com.sgcc.nfc.lock.domain.model.PagedList
import com.sgcc.nfc.lock.domain.repository.LogRepository
import javax.inject.Inject
import kotlinx.coroutines.flow.first

class LogRepositoryImpl @Inject constructor(
    private val logApi: LogApi,
    private val operationLogDao: OperationLogDao
) : LogRepository {

    override suspend fun getLogs(
        page: Int,
        pageSize: Int,
        operationType: Int?,
        lockNfcId: String?,
        startTime: String?,
        endTime: String?
    ): NetworkResult<PagedList<OperationLog>> {
        val response = safeApiCall {
            logApi.getLogs(page, pageSize, operationType, lockNfcId, startTime, endTime)
        }
        return when (response) {
            is NetworkResult.Success -> {
                val paged = response.data.map { it.toDomain() }
                operationLogDao.upsertAll(paged.data.map { it.toEntity() })
                NetworkResult.Success(paged)
            }
            is NetworkResult.Error -> {
                val local = operationLogDao.observeLogs().first().map { it.toDomain() }
                if (local.isNotEmpty()) {
                    NetworkResult.Success(PagedList(local, 1, local.size.toLong(), local.size.toLong(), 1))
                } else {
                    response
                }
            }
            NetworkResult.Loading -> NetworkResult.Loading
        }
    }
}
